package com.example.readroomforpaging3.ui.fragment

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.doOnPreDraw
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.paging.ExperimentalPagingApi
import androidx.paging.LoadState.*
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.readroomforpaging3.adapter.ArticleAdapter
import com.example.readroomforpaging3.databinding.FragmentHomeBinding
import com.example.readroomforpaging3.viewmodel.ArticleViewModel
import com.example.readroomforpaging3.viewmodel.ViewModelFactory
import com.google.android.material.transition.MaterialElevationScale
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch


class HomeFragment : Fragment() {

    private val viewModel by activityViewModels<ArticleViewModel> {
        ViewModelFactory(requireActivity())
    }

    private val articleAdapter by lazy {
        ArticleAdapter()
    }

    private var _binding: FragmentHomeBinding? = null
    private val binding get() = _binding!!

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.d("TAG", "HomeFragment: $viewModel")
    }

    @ExperimentalPagingApi
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentHomeBinding.inflate(inflater)
        binding.recycleView.apply {
            layoutManager = LinearLayoutManager(requireActivity())
            this.adapter = articleAdapter
        }
        viewLifecycleOwner.lifecycleScope.launch {
            viewModel.articlePage.collectLatest {
                articleAdapter.submitData(it)
            }
        }

        viewLifecycleOwner.lifecycleScope.launch {
            articleAdapter.loadStateFlow.collectLatest {
                when(it.refresh) {
                    is Loading -> Log.d("TAG", "refresh: Loading")
                    is NotLoading -> Log.d("TAG", "refresh: NotLoading")
                    is Error -> Log.d("TAG", "refresh: Error")
                }
                when(it.append) {
                    is Loading -> Log.d("TAG", "append: Loading")
                    is NotLoading -> Log.d("TAG", "append: NotLoading")
                    is Error -> Log.d("TAG", "append: Error")
                }
                when(it.prepend) {
                    is Loading -> Log.d("TAG", "prepend: Loading")
                    is NotLoading -> Log.d("TAG", "prepend: NotLoading")
                    is Error -> Log.d("TAG", "prepend: Error")
                }
            }
        }

        binding.refresh.setOnRefreshListener {
            when {
                it.isLoading -> {
                    Log.d("TAG", "SmartRefresh: isLoading")
                    articleAdapter.refresh()
                }
                it.isRefreshing -> {
                    Log.d("TAG", "SmartRefresh: isRefreshing")
                }
                it.autoLoadMore() -> {
                    Log.d("TAG", "SmartRefresh: autoLoadMore")
                }
            }
            binding.refresh.finishRefresh()
        }

        articleAdapter.addLoadStateListener { loadStatus ->
            when(loadStatus.refresh) {
                is Loading -> Log.d("TAG", "addLoadStateListener:refresh: Loading")
                is Nothing -> Log.d("TAG", "addLoadStateListener:refresh: Nothing")
                is Error -> Log.d("TAG", "addLoadStateListener:refresh: Error")
                else -> Log.d("TAG", "addLoadStateListener:refresh: Else")
            }
        }
        articleAdapter.addLoadStateListener { loadStatus ->
            when(loadStatus.append) {
                is Loading -> Log.d("TAG", "addLoadStateListener:append: Loading")
                is Nothing -> Log.d("TAG", "addLoadStateListener:append: Nothing")
                is Error -> Log.d("TAG", "addLoadStateListener:append: Error")
                else -> Log.d("TAG", "addLoadStateListener:append: Else")
            }
        }
        articleAdapter.addLoadStateListener { loadStatus ->
            when(loadStatus.prepend) {
                is Loading -> Log.d("TAG", "addLoadStateListener:prepend: Loading")
                is Nothing -> Log.d("TAG", "addLoadStateListener:prepend: Nothing")
                is Error -> Log.d("TAG", "addLoadStateListener:prepend: Error")
                else -> Log.d("TAG", "addLoadStateListener:prepend: Else")
            }
        }

        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        postponeEnterTransition()
        view.doOnPreDraw { startPostponedEnterTransition() }

        exitTransition = MaterialElevationScale(false).apply {
            duration = 300.toLong()
        }
        reenterTransition = MaterialElevationScale(true).apply {
            duration = 300.toLong()
        }
    }

}